//
//  ZDAccount.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/10/28.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class ZDAccount: NSObject, NSCoding {
    
    //声明类属性 记录用户是否登录
    class var isLogin: Bool {
        
        //如果能够从沙盒加载用户账号 就说明用户已登录过
        return ZDAccount.loadAccountData() != nil
    }
    
    //用于调用access_token，接口获取授权后的access token
    var access_token: String?
    
    //access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        
        didSet {
        
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    //当前授权用户的UID
    var uid: String?
    
    //access_token的生命周期
    var expires_date: NSDate?
    
    //用户友好显示名称
    var name: String?
    
    //用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    
    //MARK: - 重写构造函数  字典转模型
    init(dict: [String : AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
        print("forUndefinedKey = \(key)")
    }
    
    
    override var description: String {
    
        return "access_token = \(access_token), expires_in = \(expires_in), uid = \(uid), expires_date = \(expires_date), name = \(name), avatar_large = \(avatar_large)"
    }
    
    
    //使用static修饰的属性可以在类方法中访问
    static let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    //MARK: - 保存数据
    func saveAccountData() {
    
        NSKeyedArchiver.archiveRootObject(self, toFile: ZDAccount.filePath)
    }
    
    //保存用户账户信息
    static private var userAccount: ZDAccount?
    
    //MARK: - 加载数据  类方法
    //账户的accessToken在服务器请求时会经常使用，如果每次都从沙盒加载比较影响性能 ———— 应该缓存到内存中(定义属性保存)
    class func loadAccountData() -> ZDAccount? {
    
        //1.如果内存没有 就从沙盒加载
        if (userAccount == nil) {
        
            print("从沙盒加载")
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? ZDAccount
        }
        
        //2.从沙盒加载的不为空 并且accessToken没有过期
//        userAccount?.expires_date = NSDate(timeIntervalSinceNow: -100)   //测试日期失效
        if userAccount != nil && userAccount?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
        
            return userAccount
        }
        
        return nil
    }
    
    
    //MARK: - 加载用户信息
    func loadUserInfo(finished: (error: NSError?) -> Void) {
    
        ZDNetworkTool.sharedInstance.loadUserInfo(access_token, uid: uid) { (result, error) -> Void in
            
            if error != nil || result == nil {
            
                //请求失败
                finished(error: error)   //执行回调
                
                return
            }
            
            //请求成功
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            //保存用户信息到沙盒
            self.saveAccountData()
            
            //同步到内存中
            ZDAccount.userAccount = self
            
            //执行回调
            finished(error: nil)
        }
    }
    
    
    //MARK: - 代理方法
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        super.init()
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}


//extension ZDAccount: NSCoding {
//
//    func encodeWithCoder(aCoder: NSCoder) {
//        
//        aCoder.encodeObject(access_token, forKey: "access_token")
//        aCoder.encodeInteger(expires_in, forKey: "expires_in")
//        aCoder.encodeObject(uid, forKey: "uid")
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        
//        super.init()
//        
//        access_token = aDecoder.decodeObjectForKey("access_token")
//        expires_in = aDecoder.decodeIntegerForKey("expires_in")
//        uid = aDecoder.decodeObjectForKey("uid")
//    }
//}
